/// 本文件由reazhuang@outlook.com开发编写 *CodeMaid自动格式化*
/// SearchPanel的id设计
/// SearchPanel、内置Form、Table、Charts的id机遇同一个值加前缀
/// 1.返回表单dom内容
/// 2.获取前端的wtmtpl-searhpanel模板
/// 3.渲染模板并将模板内容插入到表单前面
/// 4.移动表单dom到模板插槽中
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Options;
using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;

namespace ReaWTM.LayuiHelper
{
	[HtmlTargetElement("wt:searchpanel", Attributes = REQUIRED_ATTR_NAME, TagStructure = TagStructure.NormalOrSelfClosing)]
	public class SearchPanelTagHelper : FormTagHelper
	{


		/// <summary>
		/// 点击重置按钮后的事件
		/// </summary>
		public string OnReseted { get; set; }

		/// <summary>
		/// 重置的同时 进行搜索
		/// </summary>
		public bool IsResetSearch { get; set; } = true;

		/// <summary>
		/// 搜索标题
		/// </summary>
		public string Title { get; set; } = THProgram._localizer["Sys.SearchCondition"];

		private IBasePagedListVM<TopBasePoco, BaseSearcher> _listVM;

		private IBasePagedListVM<TopBasePoco, BaseSearcher> ListVM
		{
			get
			{
				if (_listVM == null)
				{
					_listVM = Vm?.Model as IBasePagedListVM<TopBasePoco, BaseSearcher>;
				}
				return _listVM;
			}
		}

		private BaseSearcher _searcherVM;

		private BaseSearcher SearcherVM
		{
			get
			{
				if (_searcherVM == null)
				{
					if (ListVM == null)
					{
						_searcherVM = Vm?.Model as BaseSearcher;
					}
					else
					{
						_searcherVM = ListVM.Searcher;
					}
				}
				return _searcherVM;
			}
		}

		private string _gridIdUserSet;

		private string _gridId;

		/// <summary>
		/// 关联的 Grid 组件的 Id
		/// </summary>
		public string GridId
		{
			get
			{
				if (string.IsNullOrEmpty(_gridId))
				{
					if (string.IsNullOrEmpty(_gridIdUserSet))
					{
						if (ListVM != null)
						{
							_gridId = $"{DataTableTagHelper.TABLE_ID_PREFIX}{ListVM?.UniqueId}";
						}
					}
					else
					{
						_gridId = _gridIdUserSet;
					}
				}
				return _gridId;
			}
			set
			{
				_gridId = value;
				_gridIdUserSet = value;
			}
		}

		/// <summary>
		/// 关联的 Chart 组件的 Id
		/// </summary>
		public string ChartId { get; set; }


		/// <summary>
		/// 重置按钮
		/// </summary>
		public bool ResetBtn { get; set; }

		/// <summary>
		/// Is expanded
		/// </summary>
		public bool? Expanded { get; set; }

		private Configs _configs;

		public SearchPanelTagHelper(IOptionsMonitor<Configs> configs)
		{
			_configs = configs.CurrentValue;
		}

		private bool IsInSelector = false;


		public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
		{
			StringBuilder builder = new StringBuilder();
			SetCascadeValue(context, this);

			UseCascadeParameter<TreeContainerTagHelper>(context, x =>
			{
				x.SetDictValue("search-panel-id", Id);
				SetDictValue("tree-container-id", "wtTree_" + x.Id);
				output.Attributes.Add("tree-container-id", "wtTree_" + x.Id);
			});

			#region 兼容wtm官方方法
			if (context.Items.ContainsKey("inselector") == true)
			{
				IsInSelector = true;
			}
			if (OldPost == true)
			{
				output.Attributes.Add("oldpost", true);
			}
			#endregion

			bool show = false;
			if (SearcherVM?.IsExpanded != null)
			{
				Expanded = SearcherVM?.IsExpanded;
			}
			if (Expanded != null)
			{
				show = Expanded.Value;
			}
			else
			{
				show = _configs.UIOptions.SearchPanel.DefaultExpand;
			}

			//等待子组件渲染
			await output.GetChildContentAsync();

			builder.Append($@"
<script>
wtm.searchpanel_Render({{
id:'{Id}',
beforeMount:'{BeforeMount}',
chartIds:{GetChartIds(output)},
expanded:{GetBooleanString(show)},
gridIds:{GetGridIds()},
mounted:'{Mounted}',
resetAndSearch:{GetBooleanString(IsResetSearch)},
resetBtn:{GetBooleanString(ResetBtn)},
resetText:'{THProgram._localizer["Sys.Reset"]}',
searchText:'{THProgram._localizer["Sys.Search"]}',
show:{GetBooleanString(show)},
title:'{Title}',
treeContainerId:'{GetDictValue("tree-container-id")}',
more:'{THProgram._localizer["Sys.More"]}',
hasMore:'{GetDictValue("has-more")}',
}});
</script>
");
			output.PostElement.AppendHtml(builder.ToString());
			await base.ProcessAsync(context, output);
		}

		private string GetGridIds()
		{
			if (string.IsNullOrEmpty(GridId))
			{
				return "[]";
			}

			return JsonSerializer.Serialize(GridId.Split(','), JsonOptions);
		}

		private string GetChartIds(TagHelperOutput output)
		{
			if (string.IsNullOrEmpty(ChartId))
			{
				return "[]";
			}
			output.Attributes.SetAttribute("chartlink", ChartId);
			return JsonSerializer.Serialize(ChartId.Split(','), JsonOptions);
		}
	}
}